package master.common.utils;

import master.common.encoding.BASE64Decoder;
import master.common.encoding.BASE64Encoder;
import master.common.encoding.CharacterDecoder;
import master.common.encoding.CharacterEncoder;
import master.common.encoding.HEXDecoder;
import master.common.encoding.HEXEncoder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串工具
 * @author <a href="mailto:sealinglip@gmail.com">阳雄</a>
 *
 */
public class StringUtil {
	/**
	 * 转换Base64编码的字符串为字节数组
	 * @param base64Str
	 * @return 字节数组
	 * @throws IOException
	 */
	public static byte[] base64ToByteArray(String base64Str) throws IOException{
		CharacterDecoder decoder = new BASE64Decoder();
		return decoder.decodeBuffer(base64Str);
	}

	/**
	 * 转换字节数组为Base64编码的字符串
	 * @param origin
	 * @return Base64编码的字符串
	 */
	public static String byteArrayToBASE64(byte[] origin) {
		CharacterEncoder encoder = new BASE64Encoder();
		return encoder.encode(origin);
	}
	
	/** 
	 * 转换字节数组为16进制字串 
	 * @param b 字节数组 
	 * @return 16进制字串 
	 */

	public static String byteArrayToHexString(byte[] b) {
		return HEXEncoder.encode(b);
	}
	
	/**
	 * 转换16进制字符串为字节数组
	 * @param hexString
	 * @return 字节数组
	 */
	public static byte[] hexStringToByteArray(String hexString) {
		return HEXDecoder.decodeBuffer(hexString);
	}
	
	/**
	 * 以指定的分隔符连接对象集合
	 * @param seperator
	 * @param collection
	 * @return 连接之后的字符串
	 */
	public static String join(String seperator, Collection<?> collection) {
		if (collection == null || collection.isEmpty()) {
			return "";
		}
		Iterator<?> it = collection.iterator();
		Object obj = it.next();
		StringBuilder buf = new StringBuilder( collection.size() * String.valueOf(obj).length() )
				.append( obj );
		while ( it.hasNext() ) {
			buf.append( seperator ).append( it.next() );
		}
		return buf.toString();
	}
	
	/**
	 * 以指定的分隔符连接对象数组
	 * @param seperator
	 * @param objs
	 * @return 连接之后的字符串
	 */
	public static String join(String seperator, Object[] objs) {
		if (objs == null) {
			return "";
		}
		int length = objs.length;
		if ( length == 0 ) {
			return "";
		}
		StringBuilder buf = new StringBuilder( length * String.valueOf(objs[0]).length() )
				.append( objs[0] );
		for ( int i = 1; i < length; i++ ) {
			buf.append( seperator ).append( objs[i] );
		}
		return buf.toString();
	}

	
	/**
	 * 只替换一次，得到替换后的字符串
	 * @param template 原始字符串
	 * @param placeholder 查找的字符串
	 * @param replacement 替换的字符串
	 * @return 替换后的字符串
	 */
	public static String replaceOnce(String template, String placeholder, String replacement) {
		int loc = template.indexOf( placeholder );
		if ( loc < 0 ) {
			return template;
		} else {
			return new StringBuilder( template.substring( 0, loc ) )
					.append( replacement )
					.append( template.substring( loc + placeholder.length() ) )
					.toString();
		}
	}
	
	/**
	 * 之所以提供这个方法，是为了和String.split区分开。
	 * 这里没有采用正则表达式，而是直接基于设定字符的分割
	 * @param sourceStr
	 * @param delim
	 * @return String[]
	 */
	public static String[] split(String sourceStr, String delim) {
		StringTokenizer st = new StringTokenizer(sourceStr, delim);
		List<String> subStrList = new ArrayList<String>();
		while (st.hasMoreTokens()) {
			String element = st.nextToken();
			subStrList.add(element);
		}
		return subStrList.toArray(new String[subStrList.size()]);
	}
	
	/**
	 * 查找字符串中的所有匹配子字符串
	 * @param sourceStr
	 * @param pattern
	 * @return 字符串中的所有匹配子字符串
	 */
	public static String[] findAll(String sourceStr, Pattern pattern) {
		if (sourceStr == null || sourceStr.length() == 0) {
			return null;
		} else {
			Matcher matcher = pattern.matcher(sourceStr);
			List<String> results = new ArrayList<String>();
			while (matcher.find()) {
				results.add(matcher.group());
			}
			return results.size()>0?results.toArray(new String[results.size()]):null;
		}
	}
	
	/**
	 * 半角转全角：全角空格为12288，半角空格为32,其他字符半角(33-126)与全角(65281-65374)的对应关系是：均相差65248
	 * @param arg 任意字符串
	 * @return 全角字符串
	 */
	public static final String toSBC(String arg) {
		if (arg == null) {
			return null;
		}
		char[] c = arg.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == 32) {
				c[i] = (char) 12288;
				continue;
			}
			if (c[i] < 127) {
				c[i] = (char) (c[i] + 65248);
			}
		}
		return new String(c);
	}
	
	/**
	 * 全角转半角：全角空格为12288，半角空格为32,其他字符半角(33-126)与全角(65281-65374)的对应关系是：均相差65248
	 * @param arg 任意字符串
	 * @return 半角字符串
	 */
	public static final String toDBC(String arg) {
		if (arg == null) {
			return null;
		}

		char[] c = arg.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == 12288) {
				c[i] = (char) 32;
				continue;
			}
			if (c[i] > 65280 && c[i] < 65375) {
				c[i] = (char) (c[i] - 65248);
			}
		}
		return new String(c);
	}
}